package ar.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import ar.Location.Helper.BitmapProvider;
import ar.Location.Internet.NetworkStateReceiver;
import ar.Location.PlaceObject.PlaceCategoryManager;
import ar.Location.Setting.Settings;

public class IntroductionActivity extends Activity {

	protected static final String TAG = "IntroductionActivity";
	private ProgressBar pbIntro;
	private Thread delay;
	private Thread startMainAct;
	NetworkStateReceiver networkReceiver = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.introduction);

		PlaceCategoryManager.initListCategories();
		PlaceCategoryManager.initListDataSources();
		BitmapProvider.initBitmapProvider(this);
		
		Settings.loadSettingLanguage(getApplicationContext());
		
		pbIntro = (ProgressBar) findViewById(R.id.pbIntro);
		pbIntro.setProgress(0);
		pbIntro.setMax(1000);

		postDelayIn(1000);

		startMainActivity();
		initReceiver();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		registerReceiver(networkReceiver, new IntentFilter(
				ConnectivityManager.CONNECTIVITY_ACTION));
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(networkReceiver);
	}

	private void initReceiver() {
		// TODO Auto-generated method stub
		networkReceiver = new NetworkStateReceiver();
	}

	private void startMainActivity() {
		startMainAct = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					if (delay != null && delay.isAlive() == false) {

						Intent it = new Intent(getApplicationContext(),
								HomeActivity.class);
						startActivity(it);
						finish();
						break;
					}
				}
			}
		});
		startMainAct.start();
	}

	private void postDelayIn(final int n) {
		delay = new Thread(new Runnable() {
			@Override
			public void run() {
				for (int i = 0; i < n; i++) {
					try {
						Thread.sleep(1);
						pbIntro.setProgress(pbIntro.getProgress() + 1);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
		delay.start();
	}
}
